using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.Linq;
using System.Text;
using JwtAuthDemo.Entities;
using JwtAuthDemo.IServices;
using JwtAuthDemo.Helper;
using Microsoft.AspNetCore.Http;

namespace JwtAuthDemo.Services
{
    public class UserService : IUserService
    {
        //这里为了简化流程将用户信息写死，真正在用的时候肯定是从数据库或者其他数据源读取
        private List<User> _users=new List<User>
        {
            new User{
                Id=1,
                FirstName="yixuan",
                LastName="han",
                UserName="hanyixuan",
                Password="hanyixuan"
            
            }
        };
        private readonly AppSettings _appSettings;
        public UserService(IOptions<AppSettings> appSettings)
        {
            _appSettings=appSettings.Value;
        }
        public User Authenticate(string name, string password)
        {
            var user=_users.SingleOrDefault(x=>x.UserName==name && x.Password==password);
           //如果未找到user，则返回null
            if(user==null)
            return null;

            //否则验证成功，生成jwt token
            var tokenHandler=new JwtSecurityTokenHandler();
            var key=Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor=new SecurityTokenDescriptor
            {
                Subject=new ClaimsIdentity(new Claim[]{
                    new Claim(ClaimTypes.NameIdentifier,user.Id.ToString()),
                    new Claim(ClaimTypes.Name,user.UserName),
                    new Claim(ClaimTypes.MobilePhone,"13484058156"),
                    new Claim(ClaimTypes.Role,"admin"),
                    new Claim(ClaimTypes.Role,"admin")
                }),
                Expires=DateTime.UtcNow.AddDays(7),
                SigningCredentials=new SigningCredentials(new SymmetricSecurityKey(key),SecurityAlgorithms.HmacSha256Signature)
            };
            var token=tokenHandler.CreateToken(tokenDescriptor);
            user.Token=tokenHandler.WriteToken(token);
            return user.WithoutPassword();

        }

        public IEnumerable<User> GetAll()
        {
           
            return _users.WithoutPasswords();
        }
    }
}